using System;
using System.Xml.Serialization;
using System.IO;
using umbraco.IO;

namespace GrailTechnology.AutoTags.Providers
{
    [Serializable]
    public class Config
    {
        public static string PluginPath = "/plugins/OpenCalaisAutotag";

        public bool GenerateTagsAutomatically { get; set; }
        public bool SelectTagsAutomatically { get; set; }
        public bool AllowManualTags { get; set; }
        public bool AllowTagSuggestion { get; set; }

        public bool ShowHelp { get; set; }

		public string TagGroup { get; set; }

        public string OpenCalaisApiKey { get; set; }
        
        public string ProxyUsername { get; set; }
        public string ProxyPassword { get; set; }
        public string ProxyDomain { get; set; }

        static Config _instance;

        public string Provider { get; set; }
        public string PropertyAliasesToUse { get; set; }
        public string PropertyAliasesToExclude { get; set; }

        public ITagProvider GetProvider()
        {
            if (string.IsNullOrEmpty(Provider))
            {
                return new OpenCalaisService();
            }

            var values = Provider.Split(',');
            var service = Activator.CreateInstance(values[1].Trim(), values[0].Trim());

            if (service == null)
            {
                return new OpenCalaisService();
            }

            return (ITagProvider)service.Unwrap();
        }

        private Config()
        {
        }

        public void Write()
        {
            var s = new XmlSerializer(typeof(Config));
            string file = IOHelper.MapPath("~/config/OpenCalaisAutotag/autotags.config");
            var sw = new StringWriter();
            s.Serialize(sw, this);

            File.WriteAllText(file, sw.ToString());

        }

        public static Config Instance
        {
            get
            {
                if (_instance == null) 
                {
                    var s = new XmlSerializer(typeof(Config));
                    String conf = File.ReadAllText(IOHelper.MapPath("~/config/OpenCalaisAutotag/autotags.config"));
                    _instance = (Config)s.Deserialize(new StringReader(conf));
                }

                return _instance;
            }
        }

        public static Config TestInstance
        {
            get { return _instance ?? (_instance = new Config() { OpenCalaisApiKey = "9w9rj4vx3qyb5mqq3q9fu94u"}); }
        }
    }
}